package loveappservice.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class WxApi {

    private String appid = "wxbbb3e6daf4e1b023";
    private String secret = "958630874ad5fe268eed055e8cfc10a5";
    private String grant_type = "authorization_code";


    /**
     *   获取微信用户唯一ID：openid
     * @param code
     * @return
     */

    public String code2Session(String code) {
        //拼接请求头
        String Api_Url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid="+appid+"&"
                +"secret="+secret+"&"
                +"js_code="+code+"&"
                +"grant_type="+grant_type;

        // 设置请求头为form形式: application/x-www-form-urlencoded
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //使用RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();

        String res = restTemplate.getForObject(Api_Url,String.class);

        //转化为JSON对象
        JSONObject jsonObject = JSONObject.parseObject(res);

        try {
            String openid = jsonObject.get("openid").toString();
            if (openid == null) {
                System.out.println("没获取到openid");
            }else {
                //System.out.println("openid:"+openid);
                return openid;
            }

        }catch (Exception e){
           return "3001";

        }
        return "3002";
    }





}
